<template>
<div class="mapbox-maps">
    <div id="map">      
    </div> 
</div>   
    
</template>
<script>
export default{
  name:'MapboxClustering',
  data(){
      return{
        map:{},

      }
  },
  mounted() {
    this.loadMap()
  },
  beforeDestroy(){
    this.map.remove()

  },
  methods:{
    loadMap() {
      // 英文标注转换为中文   
      // mapboxgl.setRTLTextPlugin(
      //   "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js"
      // );
      this.map =  new mapboxgl.Map({
        accessToken: 'pk.eyJ1Ijoienh0d24iLCJhIjoiY2wzanV3bHduMTZwejNrcXcyd3B1bzBieiJ9.aW_TDqLomftwPvBu7OWqwQ',
        container: 'map',
        style: 'mapbox://styles/mapbox/outdoors-v10', // stylesheet location
        center: [-103.59179687498357, 40.66995747013945], // starting position [lng, lat]
        zoom: 3, // starting zoom
        hash: false,
        //pitch: 45,  //地图的角度，不写默认是0，取值是0-60度，一般在3D中使用
        bearing: 0, //地图的初始方向，值是北的逆时针度数，默认是0，即是正北
        antialias: true, //抗锯齿，通过false关闭提升性能
      })
      // 设置语言
      // var language = new MapboxLanguage({ defaultLanguage: "zh" });
      // this.map.addControl(language);

      //地图导航
      var nav = new mapboxgl.NavigationControl();
      this.map.addControl(nav, 'top-right');

      // 比例尺
      var scale = new mapboxgl.ScaleControl({
          maxWidth: 100,
          unit: "metric"
      });
      this.map.addControl(scale,"bottom-left");

      // 全图
      this.map.addControl(new mapboxgl.FullscreenControl());
      // 定位
      this.map.addControl(
        new mapboxgl.GeolocateControl({
        positionOptions: {
            enableHighAccuracy: true
        },
        trackUserLocation: true
        })
      );
      let that = this;
      this.map.on('load',function () {
        // 从GeoJSON数据添加一个新的源并设置“cluster”选项为true。GL-JS将把point_count属性添加到源数据中。
        // 添加数据源
        that.map.addSource("earthquakes", {
          type: "geojson",
          // Point to GeoJSON data. This example visualizes all M1.0+ earthquakes
          // from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
          data: "https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson",
          cluster: true,
          clusterMaxZoom: 14, // Max zoom to cluster points on //最大缩放到群集点
          clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50) // 每一组点的半径（=50）
        });
        // 添加圆形聚合图层 外围有数字的圆圈，加晕染
        that.map.addLayer({
          id: "clusters",
          type: "circle",
          source: "earthquakes",
          filter: ["has", "point_count"],//这个地方是返回值是countTotal，所以要改成你要展示的数字
          paint: {
            //*蓝色，当点数小于100时为20px圆
            //*点计数在100到750之间时为黄色，21px圆
            //*点计数大于或等于750时为22像素的粉红色圆圈
            "circle-color": [
              "step",
              ["get", "point_count"],
              "#51bbd6",
              100,
              "#f1f075",
              750,
              "#f28cb1"
            ],
            "circle-radius": [
              "step",
              ["get", "point_count"],
              20,//蓝色，当点数小于100时为20px圆
              100,//对应上面circle-color 数字，意思为100以内
              30,//点计数在100到750之间时为黄色，30px圆
              750,//对应上面circle-color 数字，意思为750以内
              40//点计数大于或等于750时为22像素的粉红色圆圈
            ]
          }
        });
        // 添加数字图层
        that.map.addLayer({
          id: "cluster-count",
          type: "symbol",
          source: "earthquakes",
          filter: ["has", "point_count"],
          layout: {
            "text-field": "{point_count_abbreviated}", //我们找到我们自己要展示的值
            "text-font": ["DIN Offc Pro Medium", "Arial Unicode MS Bold"],
            "text-size": 12
          },
          // 添加这个就可以改变圆圈内字样式，这里我改变了他的颜色
          paint: {
            "text-color": "#fff",
            "text-opacity": 1
          }

        });
        // 添加未聚合图层 // 聚合图中没有数字的显示小圆点
        that.map.addLayer({
          id: "unclustered-point",
          type: "circle",
          source: "earthquakes",
          filter: ["!", ["has", "point_count"]],
          paint: {
            "circle-color": "#11b4da",
            "circle-radius": 4,
            "circle-stroke-width": 1,
            "circle-stroke-color": "#fff"
          }
        });

        // inspect a cluster on click  点击聚合图层地图级别中心点变化
        that.map.on('click', 'clusters', function (e) {
          var features = that.map.queryRenderedFeatures(e.point, {
            layers: ['clusters']
          });
          console.log('features', features);
          var clusterId = features[0].properties.cluster_id;
          that.map.getSource('earthquakes').getClusterExpansionZoom(clusterId, function (err, zoom) {
            if (err) return;
            that.map.easeTo({
              center: features[0].geometry.coordinates,
              zoom: zoom
            });
          });

          // 获取当前聚合点下一级子元素
          that.map.getSource('earthquakes').getClusterChildren(clusterId, (error, features) => {
            if (!error) {
              console.log('Cluster children:', features);
            }
          });

          // 获取当前聚合点下边的所有子元素
          let allFeatures = [];
          const getFeatures = (id) => {
            that.map.getSource('earthquakes').getClusterChildren(id, (error, features) => {
              features.forEach(feature => {
                const {id=''} = feature;
                id && getFeatures(id);
                !id && allFeatures.push(feature);
                console.log('allFeatures', allFeatures);
              });
            });
          };
          
          getFeatures(clusterId);
        });
        // 聚合图层鼠标移入样式
        that.map.on('mouseenter', 'clusters', function (e) {
            console.log('cluster', e);
            that.map.getCanvas().style.cursor = 'pointer';
        });
        // 聚合图层鼠标移出鼠标样式
        that.map.on('mouseleave', 'clusters', function () {
            that.map.getCanvas().style.cursor = '';
        });
        let popup = new mapboxgl.Popup({
            className: 'my-class'
        });
        // 未聚合图层鼠标移入pop框显示
        that.map.on('mouseenter', 'unclustered-point', function (e) {
            console.log(e)
            // 改变鼠标样式
            that.map.getCanvas().style.cursor = 'pointer';
            let features = e.features[0].properties;
            popup.setLngLat(e.lngLat)
            popup.setHTML(`<h3>id: ${features.id}</h3><h3>time: ${features.time}</h3>`)
            popup.setMaxWidth("300px")
            popup.addTo(that.map);
        });
        // 未聚合图层鼠标移出pop框隐藏
        that.map.on('mouseleave', 'unclustered-point', function () {
            // 改变鼠标样式
            that.map.getCanvas().style.cursor = '';
            popup.remove();
        });          
      })          
    },        
  }
}

</script>
<style  scoped lang="scss">
@import "../../../public/mapbox/mapbox-gl.css";
.mapbox-maps {
  width: 100%;
  height: calc(100vh - 50px);
  position: relative;
  #map {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    bottom:0;
    right: 0;        
  }
    
}
.mapboxgl-canvas {
  outline: none;
}
  /* 隐藏mapbox商标 */
.mapboxgl-ctrl-logo {
  display: none;
} 
</style>